<script setup lang="ts">
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryGoods } from '@/api/category'
import type { findSubCategoryGoodsItemType } from '@/types/category'
// 引入route
const route = useRoute()
// 数据加载状态
const loading = ref<boolean>(false)
// 数据是否全部加载完成
const finished = ref<boolean>(false)
// 查询参数
let params: any = {
  id: route.params.id,
  page: 1, // 当前页数
  pageSize: 20 // 每页条数
}
// 渲染数组
const goodsList = ref<findSubCategoryGoodsItemType[]>([])
// 请求数据
const getData = async () => {
  // 开始加载数据
  loading.value = true
  const res = await findSubCategoryGoods(params)
  if (res.result.items.length) {
    // 判断如果有数据，则追加
    goodsList.value.push(...res.result.items)
    // 页数加一
    params.page++
  } else {
    // 无数据则代表全部加载完毕
    finished.value = true
  }
  // 本次加载完毕
  loading.value = false
}
// 当路由变化时，清空数组重新请求
watch(
  () => route.params.id,
  (newVal) => {
    if (newVal && route.path === `/category/sub/${newVal}`) {
      goodsList.value = []
      finished.value = false
      params.id = newVal
      params.page = 1
      params.attrs?.length && delete params.attrs
    }
  }
)
// 监听排序改变
const changeSort = (sortParams: {
  inventory: boolean | null
  onlyDiscount: boolean | null
  sortField: null | string
  sortMethod: null | string
}) => {
  // 合并参数
  params = { ...params, ...sortParams, page: 1 }
  goodsList.value = []
  finished.value = false
}
// 监听筛选属性变化
const changeFilter = (filterParams: any) => {
  // 合并参数
  params = { ...params, ...filterParams, page: 1 }
  goodsList.value = []
  finished.value = false
}
</script>

<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区域 -->
      <SubFilter @filter-change="changeFilter" />
      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="changeSort" />
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id">
            <GoodsItem :goods="item" />
          </li>
        </ul>
        <!-- 加载组件 -->
        <XtxInfiniteLoading
          :loading="loading"
          :finished="finished"
          @infinite="getData"
        />
      </div>
    </div>
  </div>
</template>
<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
